package com.example.demo.use_demo.a_encrypt;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.spec.SecretKeySpec;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import static java.util.Arrays.copyOf;

/**
 * key初始化器
 * @author weiqingjing@jd.com
 * @date 2021/12/13 7:05 PM
 */
public class KeyInitializer {
    private KeyInitializer() {
    }

    public static String secretKeySpecBase64Init(String salt) {
        byte[] key = DigestUtils.sha1(salt);
        key = copyOf(key, 128 / 8);
        return Base64.encodeBase64String(key);
    }

    public static SecretKeySpec secretKeySpecInit(String salt) {
        byte[] key = DigestUtils.sha1(salt);
        key = copyOf(key, 128 / 8);
        return new SecretKeySpec(key, "AES");
    }

    public static PrivateKey privateKeyInit(String base64KeyStr) {
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                Base64.decodeBase64(base64KeyStr));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static PublicKey publicKeyInit(String base64KeyStr) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePublic(
                new X509EncodedKeySpec(Base64.decodeBase64(base64KeyStr)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
